package at.codebase.web.util.servlet;

import java.util.ArrayList;
import java.util.logging.Logger;

import org.json.simple.JSONObject;

import at.codebase.db.dao.EApiAccessDao;
import at.codebase.web.util.LocalRequest.RequestInformation;
import at.codebase.web.util.URLParameters.ParameterDoesNotExistException;

@SuppressWarnings("unchecked")
public abstract class ApiSecureServlet extends SecureServlet {
	/*
	private static HashMap<String, EApiAccess> accesses = new HashMap<String, EApiAccess>();	
	
	*/
	public static final Logger log = Logger.getLogger(ApiSecureServlet.class
			.getName());
	
	private static JSONObject successResult = new JSONObject();
	private static JSONObject errorResult = new JSONObject();
	
	static {
		//reloadAccessTokens();
		successResult.put("success", new Boolean(true));
		successResult.put("message", "");
		
		errorResult.put("success", new Boolean(false));
		errorResult.put("message", "");
	}
	
	/*
	public static void reloadAccessTokens(){
		List<EApiAccess> apiAccessList = EApiAccessDao.getApiAccessList();
		accesses.clear();
		for(EApiAccess apiAccess:apiAccessList){
			if(apiAccess.isActive()){
				accesses.put(apiAccess.getAccessToken(), apiAccess);
			}
		}
	}
	*/


	@Override
	protected void initSecurityLevels(ArrayList<UserLevel> secLevels) {
		secLevels.add(UserLevel.ANONYMOUS);
		secLevels.add(UserLevel.REGISTERED);
		secLevels.add(UserLevel.ADMIN);
	}
	
	/*
	 * Let ApiSecureServlet implement SecureAjaxSerlvet than SecureServlet to
	 * change content type from html to json and only allow post requests.
	 */
	@Override
	final protected RequestType requestType() {
		return RequestType.POST_AND_GET;
	}
	
	@Override
	final protected String getContentType() {
		return "application/json";
	}
	/*
	 * 
	 */
	
	@Override
	protected void processRequestSecurityLevel(RequestInformation requestInfo, UserLevel level, RequestType requestType) {
		JSONObject result = null;
		try {
			String authToken = requestInfo.getParameters().getString("auth_token");
			if(authToken != null && EApiAccessDao.isValid(authToken)){
				result = processRequest(requestInfo, authToken);
			}else{
				result = badRequestResult("auth_token invalid ");
			}
		} catch (ParameterDoesNotExistException e) {
			result = badRequestResult("no auth_token " + String.valueOf(requestInfo.getParameters().getParameterNames().size()));
		}
		log.severe("result: "+result.toJSONString());
		writer().printInsecure(result.toJSONString());
	}
	
	protected abstract JSONObject processRequest(RequestInformation requestInfo, String authToken);
	
	public static JSONObject badRequestResult(String msg){
		JSONObject result = (JSONObject) errorResult.clone();
		result.put("message", msg);
		return result;
	}
	
	public static JSONObject successResult(){
		JSONObject result = (JSONObject) successResult.clone();
		result.put("message", "");
		return result;
	}
	
}
